<template>
  <div>
    <template v-for="(template, index) in templateList" :key="index">
      <el-form
        :model="template.formData"
        :rules="template.rules"
        :ref="(el) => (formRefs[index] = el)"
        v-bind="template.formConfig"
      >
        <el-card>
          <template v-for="(field, index) in template.fields" :key="index">
            <FieldComponent :field="field" :formData="template.formData" />
          </template>
        </el-card>
        <el-form-item>
          <el-button type="primary" @click="submitForm(index)">提交</el-button>
        </el-form-item>
      </el-form>
    </template>
  </div>
</template>

<script setup>
import FieldComponent from './FieldComponent.vue';
import { onMounted, ref, watch } from 'vue';
import { calculateFunction, initFormData } from './js/FieldComponent.js';
import { ElMessage } from 'element-plus';

const formJson = ref({});

onMounted(() => {
  getJson();
});

function getJson() {
  fetch('/json/demo.json').then((response) => {
    response.json().then((data) => {
      console.log(data);
      formJson.value = data;
      console.log(formJson);
      initForm();
    });
  });
}

const formRefs = ref([]);

// 提交表单并进行校验
function submitForm(index) {
  const formRef = formRefs.value[index];
  if (formRef) {
    formRef.validate((valid, invalidFields) => {
      if (valid) {
        console.log('表单验证成功:', templateList.value[index].formData);
      } else {
        ElMessage.error('表单验证失败！');
        for (const field in invalidFields) {
          ElMessage.error(invalidFields[field][0].message);
        }
      }
    });
  }
}

const templateList = ref([]);

function initForm() {
  templateList.value.push(formJson.value);

  templateList.value.forEach((template) => {
    template.formData = initFormData(template);
  });

  // 监听 formData 的变化
  templateList.value.forEach((template, index) => {
    watch(
      () => template.formData,
      (newVal, oldVal) => {
        calculateFunction(template, template.formData);
        // 在这里处理变化后的逻辑
      },
      { deep: true }
    ); // 深度监听以捕捉对象内部值的变化
  });
}
</script>

<style scoped lang="scss"></style>
